package com.lenovo.lcdmoauth.config;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.JdbcOperations;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2ClientAuthenticationToken;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;

import java.util.List;
import java.util.Map;

@Slf4j
public class CustomRevocationAuthenticationProvider implements AuthenticationProvider {

    private JdbcOperations jdbcOperations;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        CustomRevocationAuthenticationToken customRevocationAuthenticationToken = (CustomRevocationAuthenticationToken) authentication;
        OAuth2ClientAuthenticationToken clientPrincipal = SecurityUtils.getAuthenticatedClientElseThrowInvalidClient(customRevocationAuthenticationToken);
        RegisteredClient registeredClient = clientPrincipal.getRegisteredClient();

        List<Map<String, Object>> maps = this.jdbcOperations.queryForList("SELECT id, registered_client_id as \"registeredClientId\" FROM oauth2_authorization WHERE principal_name = ?", customRevocationAuthenticationToken.getItcode());
        Map<String, Object> authorization = CollectionUtil.isEmpty(maps) ? null : maps.get(0);
        if (CollectionUtil.isEmpty(maps)) {
            if (log.isTraceEnabled()) {
                log.info("Did not authenticate token revocation request since token was not found");
            }
        } else if (!registeredClient.getId().equals(authorization.get("registeredClientId"))) {
            throw new OAuth2AuthenticationException("invalid_client");
        } else {
            int row = jdbcOperations.update("delete from oauth2_authorization where id = ?", String.valueOf(authorization.get("id")));
            if (log.isTraceEnabled()) {
                log.trace("Saved authorization with revoked token");
                log.trace("Authenticated token revocation request");
            }
        }
        return customRevocationAuthenticationToken;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return CustomRevocationAuthenticationToken.class.isAssignableFrom(authentication);
    }

    public void setJdbcOperations(JdbcTemplate jdbcTemplate) {
        this.jdbcOperations = jdbcTemplate;
    }
}
